<?php

/**
 * @filename source_module.php 2013-11-11 02:10:56x
 * @author Huming Xu <huming17@126.com>
 * @version 1.0.0
 * @copyright DZF (c) 2013, Huming Xu
 */
class ctrl_user_cart extends user_cart {

    public $info_array = array();
    public $page_array = array();
    public $tree_array = array();

    static function &instance() {
        static $object;
        if (empty($object)) {
            $object = new self();
        }
        return $object;
    }

    /*
     * 	取出一条信息
     */

    public function do_detail($tc_id = '') {
        global $_G;
        $detail = array();
        $cm_id = isset($_REQUEST['cm_id']) ? $_REQUEST['cm_id'] : '';
        $detail = $this->one_info('user_cart', 'cm_id', $cm_id);
        $course_info = self::get_field_value_by_id('course_main', 'cm_id', $detail['cm_id'], 'cm_id,cm_name,cm_brief,cm_img,cm_price,cm_count,so_id,so_id,cm_hour_num');
        unset($detail['create_dateline']);
        unset($detail['modify_dateline']);
        foreach ($course_info AS $key => $value) {
            $detail[$key] = $value;
        }
        //DEBUG 获取课程信息
        //DEBUG 调试输出
        if ($_G['gp_api']) {
            $return['code'] = '0';
            $return['data'][$_G['gp_mod']][$_G['gp_action']][$_G['gp_do']] = $detail;
            echo format_data($return, $_G['gp_api'], $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        } else {
            $multipage = multi($page_result['total_rows'], $perpage, $page, "index.php?mod=user&action=cart&do=index&keyword=" . $keyword);
            include template('trade/course/detail');
        }
    }

    /*
     * 添加购物车
     */
    public function do_add() {
        global $_G;
        
        $cm_id = isset($_REQUEST['cm_id']) && !empty($_REQUEST['cm_id']) ? $_REQUEST['cm_id'] : 0;
        
        if(!$_G['user_id']){//用户未登录
            $return['code'] = '3';//用户未登录
            $return['data']['user_cart_count'] = 0;
            echo format_data($return, $_G['gp_api'], $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
            return false;
        }
        //2016-12-16 09:17:46 
        //1.先判断用户提交过来的课程是否存在
        if(!$cm_id){
            //如果前端根本没传递过来课程号组合的话，直接返回
            $return['code'] = '4';//未选中要新增的课程

            $return['data']['user_cart_count'] = $this->count('user_cart', " and user_id = '".$_G['user_id']."' ");
            echo format_data($return, $_G['gp_api'], $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
            return false;
        }

        $sign = 1;
        //需要先过滤一下传递过来的课程数组中是否有课程不存
        $isHas = $this->isHasCmId($cm_id);
        if(!$isHas){//如果存在课程不存在的状态 直接终止接下来的循环
            $return['code'] = '2';//存在课程已下架或不在购买时间范围内或不存在
            $sign = 0;
        }

        if($sign){//如果该课程存在，此时进入下一重判断，判断课程是否已被购买过
            $isBuy = $this->isBuyCmId($_G['user_id'], $cm_id);
            if($isBuy){//如果存在课程已购买s的状态 直接终止接下来的循环
                $return['code'] = '5';//存在课程已购买
                $sign = 0;
            }
        }

        if($sign){//如果该课程存在并且已购买，此时进入下一重判断，判断课程是否已存在购物车
            $isCarting = $this->isAlreadyCartCmId($_G['user_id'], $cm_id);
            if($isCarting){//如果存在课程已存在购物车 直接终止接下来的循环
                $return['code'] = '6';//存在课程已在购物车
                $sign = 0;
            }
        }
        
//        if($sign){//判断此课程是否已经购买但是尚未支付
//            $isWaiting = $this->isWaitToBuyCmId($_G['user_id'], $cm_id);
//            if($isWaiting){//如果存在课程已下过单，请在我的订单中继续处理
//                $return['code'] = '7';//此课程已下过单，请在我的订单中继续处理
//                $sign = 0;
//            }
//        }
        
        if(!$sign){//如果检测出有问题，此处进行返回处理
            $return['data']['user_cart_count'] = $this->count('user_cart', " and user_id = '".$_G['user_id']."' ");
            echo format_data($return, $_G['gp_api'], $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
            return false;
        }

        //走到此处说明要新增到购物车的课程都没问题，此处进行新增处理
        $user_cart_add['user_id'] = $_G['user_id'];
        $user_cart_add['create_dateline'] = TIMESTAMP;
        $user_cart_add['cm_id'] = $cm_id;
        $r = $this->add('user_cart', $user_cart_add);

        if($r){
            $return['code'] = '0';
        }
        else{
            $return['code'] = '1';
        }
        
        //DEBUG 获取用户购物车内数量
        $return['data']['user_cart_count'] = $this->count('user_cart', " and user_id = '".$_G['user_id']."' ");
        echo format_data($return, $_G['gp_api'], $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        return false;
    }
    /*
     *  添加系统信息
     */
    public function do_num() {
        global $_G;
        if ($_G['gp_api']) {
            //TODO 后端字段校验 根据具体业务逻辑添加
            $client = isset($_REQUEST['client']) ? $_REQUEST['client'] : 'wap';
            //DEBUG 获取课程信息
            if ($_G['gp_api']) {
                //DEBUG 获取用户购物车内数量
                $wheresql = " AND user_id='".$_G['user_id']."' ";
                $user_cart_count=$this->count('user_cart',$wheresql);
                if ($_G['user_id']) {
                    $return['code'] = '0';
                    $return['data'] = array('num'=>$user_cart_count);
                } else {
                    $return['code'] = '1';
                    $return['data'] = array('num'=>"0");
                }
                echo format_data($return, $_G['gp_api'], $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
            }
        } else {
            //include template('trade/course/add');
        }
    }
    /*
     *  编辑系统信息
     */

    public function do_edit_todo() {
        global $_G;

    }

    /*
     *  删除系统信息
     */

    public function do_delete() {
        global $_G;
        $user_cart = isset($_REQUEST['user_cart']) && !empty($_REQUEST['user_cart']) ? $_REQUEST['user_cart'] : '';
        $user_cart['user_id'] = $_G['user_id'];
        if($user_cart['user_id'] && !empty($user_cart['cm_id'])){
            $wheresql = " cm_id IN (".  dimplode($user_cart['cm_id']).") AND user_id='".$user_cart['user_id']."' ";
            $effect_row = $this->delete("user_cart", $wheresql, $limit = 100);
        }
        $client = isset($_REQUEST['client']) ? $_REQUEST['client'] : 'wap';
        //DEBUG 获取课程信息
        if ($_G['gp_api']) {
            if ($effect_row) {
                $return['code'] = '0';
            } else {
                $return['code'] = '1';
            }
            if ($client == 'pc') {
                $return['data'] = array();
            } else {
                $return['data'][$_G['gp_mod']][$_G['gp_action']][$_G['gp_do']] = array();
            }
            $wheresql = " AND user_id='".$user_cart['user_id']."' ";
            $return['data']['user_cart_count']=$this->count('user_cart',$wheresql);
            echo format_data($return, $_G['gp_api'], $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        }else{
            if ($effect_row) {
                showmessage('删除成功', 'index.php?mod=user&action=cart&do=index');
            } else {
                showmessage('删除失败', 'index.php?mod=user&action=cart&do=index');
            } 
        }
    }

    /*
     *  购物车
     */

    public function do_index() {
        global $_G;
        $default_limit = 1000;
        $page = max(1, intval($_GET['page']));
        $perpage = $limit = isset($_REQUEST['limit']) && !empty($_REQUEST['limit']) ? $_REQUEST['limit'] : $default_limit;
        $start = (($page - 1) * $perpage);
        $wheresql = " AND user_id='" . $_G['user_id'] . "' AND isdelete=0 ";
        $orderby = " ORDER BY create_dateline DESC ";
        //DEBUG 初始化请求请求获取一页列表数据的参数
        $page_condition = array(
            'page' => $page, //int 请求页面 页码
            'limit' => $limit, //int 每页请求个数
            'perpage' => $perpage, //int 每页显示个数
            'wheresql' => $wheresql, //string //条件SQL语句 
            'orderby' => $orderby, //string 排序规则
        );
        //DEBUG 列表数据返回结构
        /*
          $page_result = array(
          //int 返回结果总数
          'total_rows' => $total_rows,
          //array 一页数据数组
          'page_data' => $page_data
          );
         */
        $page_result = $this->index('user_cart', $page_condition);
        foreach ($page_result['page_data'] AS $key => $value) {
            $page_result['page_data'][$key] = $value['cm_id'];
        }
        $course_info = self::get_field_value_by_id('course_main', 'cm_id', $page_result['page_data'], 'cm_cate_id,cm_start_time,cm_brief,cm_id,cm_name,cm_brief,cm_img,cm_price,cm_count,so_id,so_id,cm_hour_num,create_dateline');
        unset($page_result['page_data']);
        $client = isset($_REQUEST['client']) ? $_REQUEST['client'] : 'wap';
        if ($client == 'pc') {
            //{ type: 1, startTime: '2016-09-01', title: 'C++程序设计', price: 200, school: '嘉兴智慧教育', id: '1', img: '/images/310.png', info: '课程简述', times: '10' },
            foreach ($course_info AS $key => $value) {
                $tmp = array();
                $tmp['type'] = $value['cm_cate_id'];
                $tmp['startTime'] = date('Y-m-d', $value['cm_start_time']);
                $tmp['title'] = $value['cm_name'];
                $tmp['price'] = $value['cm_price'];
                $tmp['school'] = $this->get_field_value_by_id('school_online', 'so_id', $value['so_id'], 'so_name');
                $tmp['id'] = $value['cm_id'];
                $tmp['img'] = $value['cm_img'];
                $tmp['info'] = $value['cm_brief'];
                $tmp['times'] = $value['cm_hour_num'];
                $page_result['page_data'][] = $tmp;
            }
        }
        //DEBUG 获取课程信息

        if ($_G['gp_api']) {
            $return['code'] = '0';
            if ($client == 'pc') {
                $return['data'] = $page_result['page_data'];
            } else {
                $return['data'][$_G['gp_mod']][$_G['gp_action']][$_G['gp_do']] = $page_result;
            }
            echo format_data($return, $_G['gp_api'], $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        } else {
            $multipage = multi($page_result['total_rows'], $perpage, $page, "index.php?mod=user&action=cart&do=index");
            include template('trade/course/index');
        }
    }

    /**
     * 接口 AJAX或外部请求检索数据
     *
     * @param $return_type string json/xml.
     *
     * @return print string json/xml.
     */
    public function do_api() {
        $return = '';
        $page = max(1, intval($_GET['page']));
        $perpage = $limit = 20;
        $start = (($page - 1) * $perpage);
        $keyword = isset($_REQUEST['keyword']) ? $_REQUEST['keyword'] : '';
        $return_type = isset($_REQUEST['return_type']) ? $_REQUEST['return_type'] : 'json';
        $wheresql = "";
        if ($keyword) {
            $wheresql = " WHERE title LIKE '%" . $keyword . "%'";
        }
        $orderby = " ORDER BY tc_id DESC ";
        //DEBUG 初始化请求请求获取一页列表数据的参数
        $page_condition = array(
            'page' => $page, //int 请求页面 页码
            'limit' => $limit, //int 每页请求个数
            'perpage' => $perpage, //int 每页显示个数
            'wheresql' => $wheresql, //string //条件SQL语句 
            'orderby' => $orderby, //string 排序规则
        );
        //DEBUG 列表数据返回结构
        /*
          $page_result = array(
          //int 返回结果总数
          'total_rows' => $total_rows,
          //array 一页数据数组
          'page_data' => $page_data
          );
         */
        $page_result = $this->api('user_cart', $page_condition);
        if ('json' == $return_type) {
            $return = json_encode($page_result);
        } elseif ('xml' == $return_type) {
            $return = array2xml($page_result);
        }
        //DEBUG 接口响应直接输出返回
        echo $return;
    }

}

?>